package com.aiyi.server.manager.nginx.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.ValidationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aiyi.server.manager.nginx.bean.NginxService;
import com.aiyi.server.manager.nginx.bean.nginx.NginxConf;
import com.aiyi.server.manager.nginx.bean.result.Result;
import com.aiyi.server.manager.nginx.common.Vali;
import com.aiyi.server.manager.nginx.manager.NginxManager;

/**
 * @Auther: 郭胜凯
 * @Date: 2019-04-22 15:11
 * @Email 719348277@qq.com
 * @Description: 高级管理页
 */
@Controller
@RequestMapping("admin/sys/high")
public class HighManagerController {

    private static final Logger logger = LoggerFactory.getLogger(HighManagerController.class);

    @Resource
    private NginxManager nginxManager;

    /**
     * 高级管理页面
     * @return
     */
    @RequestMapping("/")
    public String HighPage(Integer nginxId, Model model){
    	Integer currentId = null;
    	String confText = null;
    	
    	List<NginxService> nginxServiceList = nginxManager.getNginxServiceList();
    	List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
    	for(NginxService nginxService:nginxServiceList) {
    		Map<String, Object> itemMap = new HashMap<String, Object>();
    		itemMap.put("id", ""+nginxService.getId());
    		itemMap.put("configPath", nginxService.getNginxConfigPath());
    		
    		if(currentId==null) {
    			currentId = nginxService.getId();
    			confText = nginxService.getConfText(null);
    		}else if(nginxId!=null&&nginxId!=currentId) {
    			currentId = nginxService.getId();
    			confText = nginxService.getConfText(null);
    		}
    		
    		list.add(itemMap);
    	}
    	
        model.addAttribute("list", list);
    	
        model.addAttribute("currentId", currentId);
        model.addAttribute("confText", confText);
        
        return "admin/high/index";
    }

    /**
     * 获取配置信息
     * @return
     */
    @RequestMapping(value = "/conf", method = RequestMethod.GET)
    @ResponseBody
    public Result conf(Integer nginxId, String encodeing){
        Result result = new Result();
    	
    	try {
        	NginxService nginxService = nginxManager.getServiceBy(nginxId);
			
			Map<String, Object> model = new HashMap<String, Object>();
			model.put("id", ""+nginxService.getId());
			model.put("configPath", nginxService.getNginxConfigPath());
			model.put("confText", nginxService.getConfText());
			model.put("encodeing", nginxService.getEncoding());
			
			result.setResult(model);
	        result.setSuccess(true);
	        logger.info("调试：nginxId="+nginxId+" encodeing1="+encodeing+"  encodeing2="+nginxService.getEncoding()+" 结果正常");
		} catch (Exception e) {
			e.printStackTrace();
	        result.setSuccess(false);
	        result.setMessage("错误："+e.getMessage());
		}
        
        
        return result;
    }

    @RequestMapping("conf/check")
    @ResponseBody
    public String check(@RequestBody NginxConf conf){
    	Integer nginxId = conf.getId();
    	
    	NginxService nginxService = nginxManager.getServiceBy(nginxId);
    	
        String confStr = conf.getConf();
        if (Vali.isEpt(confStr)){
            throw new ValidationException("配置文件内容不能为空");
        }
        nginxService.check(confStr);
        return "SUCCESS";
    }

    /**
     * 获取当前最新配置信息(刷新操作)
     * @return
     */
    @RequestMapping(value = "conf/refresh", method = RequestMethod.GET)
    @ResponseBody
    public String refresh(Integer nginxId, String encodeing){
    	NginxService nginxService = nginxManager.getServiceBy(nginxId);
    	
        return nginxService.getConfText(encodeing);
    }

    @PutMapping("conf/save")
    @ResponseBody
    public String save(@RequestBody NginxConf conf){
        String confStr = conf.getConf();
        
        NginxService nginxService = nginxManager.getServiceBy(conf.getId());
        
        String backConf = nginxService.getConfText(conf.getEncodeing());
        
        if (Vali.isEpt(confStr)){
            throw new ValidationException("配置文件内容不能为空");
        }

        //尝试写到Nginx配置文件
        try {
        	nginxService.save(confStr);
            //重启Nginx
            nginxService.reload();
        } catch (Exception e) {
            //恢复到上一次配置
        	nginxService.save(backConf);
            throw new ValidationException("已取消保存操作:" + e.getMessage(), e);
        }
        return "SUCCESS";
    }
}